<?php
namespace app\portal\controller;

use cmf\controller\HomeBaseController;
use app\admin\service\ApiService;
use think\Db;

class MessageController extends HomeBaseController
{

	//留言诉求页面
	public function index()
	{

		$img = Db::name('img')->find(6);
		$this->assign('img',$img);

		$userid = cmf_get_current_user_id();
		$user = Db::name('member')
		->alias('a')
		->join('cmf_wechat_department_user b','a.openid=b.user_id')
		->join('cmf_wechat_department c','c.id=b.department_id')
		->field('c.name as name,a.user_login,a.mobile,a.id')
		->where('a.id',$userid)
		->find();
		$this->assign('user',$user);
		$sort = Db::name('message_sort')->select()->toArray();
		$this->assign('sort',$sort);
		return $this->fetch();
	}

	public function indexlist()
	{

		$img = Db::name('img')->find(6);
		$this->assign('img',$img);
		
		$userid = cmf_get_current_user_id();
		$data = Db::name('message')
		->alias('a')
		->join('cmf_message_sort b','a.type=b.id')
		->where('a.user_id',$userid)
		->select();
		$this->assign('data',$data);
		return $this->fetch();
	}

	//留言诉求接口
	public function addPost()
	{
		$data = $this->request->param();
		$data['user_id'] = cmf_get_current_user_id();
		$data['time'] = time();
		$data['imgs'] = [];
		$base64_image_content = $data['img'];
		if (empty($data['content'])) {
			echo json_encode(array('msg'=>"内容不能为空！",'status'=>0));return;
		}
		for ($i=0,$count = count($base64_image_content); $i < $count; $i++) { 
			//匹配出图片的格式
			if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $base64_image_content[$i], $result)){
				$type = $result[2];
				$filename1 = 'upload/';
				$filename2 = "message/".date('Ymd',time())."/";
				$new_file = $filename1.$filename2;
				if(!file_exists($new_file))
				{
					//检查是否有该文件夹，如果没有就创建，并给予最高权限
					mkdir($new_file, 0777,true);
				}
				$uniqidtype = uniqid().".{$type}";
				$new_file = $new_file.$uniqidtype;
				if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $base64_image_content[$i])))){
					$data['imgs'][$i] = $filename2.$uniqidtype;
				}else{
					echo json_encode(array('msg'=>"图片有误",'status'=>0));exit();
					break;
				}
			}
		}
		unset($data['img']);
		$data['imgs'] = json_encode($data['imgs']);

		$res = Db::name('message')->insert($data);
		if ($res) {
			$result = json_encode(array('msg'=>"提交成功",'status'=>1,'url'=>"http://".$_SERVER['HTTP_HOST'].url('indexlist')));
		}else{
			$result = json_encode(array('msg'=>"提交失败",'status'=>0));
		}
		echo $result; return;
	}	
}